package com.idefav.service.impl;

import com.idefav.mapper.TdUserMapper;
import com.idefav.mapper.TdUserdetailMapper;
import com.idefav.mapper.UserMapper;
import com.idefav.pojo.TdUser;
import com.idefav.pojo.TdUserExample;
import com.idefav.pojo.TdUserdetail;
import com.idefav.service.UserService;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by wzs on 2017/7/15.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private TdUserMapper userMapper;

    @Autowired
    private TdUserdetailMapper userdetailMapper;

    @Autowired
    private UserMapper allUserMapper;

    @Override
    public List<TdUser> getAllUser() {
        TdUserExample example = new TdUserExample();
        TdUserExample.Criteria criteria = example.createCriteria();
        criteria.andIsdelEqualTo((byte) 0);
        List<TdUser> tdUsers = userMapper.selectByExample(example);
        return tdUsers;
    }

    @Override
    public TdUser getUserById(int uid) {

        return allUserMapper.getUserById(uid);
    }

    @Override
    public boolean addUser(TdUser user) {
        try {
            // 判断是否存在
            TdUserExample example = new TdUserExample();
            TdUserExample.Criteria criteria = example.createCriteria();
            criteria.andUidEqualTo(user.getUid());


            if (userMapper.countByExample(example) > 0) {
                return false;
            }
            int result = userMapper.insertSelective(user);

            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public int getTotalCount() {
        TdUserExample example=new TdUserExample();

        int i = userMapper.countByExample(example);
        return i;
    }

    @Override
    public int getUid() {
        TdUserExample example=new TdUserExample();
        TdUserExample.Criteria criteria = example.createCriteria();
        example.setOrderByClause(" uid desc ");

        List<TdUser> tdUsers = userMapper.selectByExample(example);
        if(tdUsers!=null &&tdUsers.size()>0){
            return tdUsers.get(0).getUid()+1;
        }
        return 1;
    }

    @Override
    public boolean addUserDetail(TdUserdetail tdUserdetail) {
        int result2 = userdetailMapper.insertSelective(tdUserdetail);
        return result2>0;
    }

    @Override
    public boolean removeUser(int uid) {
        int i = userMapper.deleteByPrimaryKey(uid);
        int i1 = userdetailMapper.deleteByPrimaryKey(uid);
        return i>0&&i1>0;
    }
}
